package com.visionblue.business.ship.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.doOnTextChanged
import com.visionblue.business.ship.R
import com.visionblue.business.ship.util.MLog
import com.visionblue.business.ship.util.ext.setVisible
import kotlinx.android.synthetic.main.view_add_sub.view.*
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * @author: xlh
 * @date: 2020-06-03 11:29 AM
 * @desc:
 */
class AddSubTextView(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) {

    private var addSubVal: BigDecimal = BigDecimal.ONE
    private var value: BigDecimal? = null
    private var decimalBits: Int = 3

    init {
        LayoutInflater.from(context).inflate(R.layout.view_add_sub, this)
        ivAdd.setOnClickListener {
            var currVal: BigDecimal = this.value ?: return@setOnClickListener
            currVal += addSubVal
            if (currVal < BigDecimal.ZERO) {
                return@setOnClickListener
            }
            setText(currVal.setScale(decimalBits, RoundingMode.HALF_DOWN))
        }

        ivSub.setOnClickListener {
            var currVal: BigDecimal = this.value ?: return@setOnClickListener
            currVal -= addSubVal
            if (currVal < BigDecimal.ZERO) {
                return@setOnClickListener
            }
            setText(currVal.setScale(decimalBits, RoundingMode.HALF_DOWN))
        }

        etInput.doOnTextChanged { text, _, _, _ ->
            if (text.isNullOrEmpty()) {
                value = BigDecimal.ZERO
            } else {
                value = BigDecimal(text.toString())
            }
        }
    }

    //todo
    fun setText(value: BigDecimal) {
        this.value = value
        etInput.setText("$value")
    }

    fun setUnit(unitText: CharSequence) {
        tvUnit.text = unitText
    }

    fun changeMode(mode: Int) {
        if (mode == EDIT_MODE) {
            ivAdd.setVisible(true)
            ivSub.setVisible(true)
            etInput.isEnabled = true
            view_divider.visibility = View.VISIBLE
        } else {
            ivAdd.setVisible(false)
            ivSub.setVisible(false)
            etInput.isEnabled = false
            view_divider.visibility = View.GONE
        }
    }

    fun setAddSubVal(value: BigDecimal, decimalBits: Int = 3) {
        addSubVal = value
        this.decimalBits = decimalBits
    }

    fun input(): EditText = etInput


    fun getVal() = value


    companion object {

        const val EDIT_MODE = 1
        const val TEXT_MODE = 2
    }

}